import { Modal } from '@tencent/corgi-ui'
import $getScript from './getScript'
import $env from '../model/env'
import callApp from './callApp'

let currentPlayer = null

let enableTestVideo = $env.enableTest

let testPath = ''
if (enableTestVideo) {
	testPath = '/test'
}

let videoPath = `//s.yangshipin.cn${testPath}/txp`
let livePath = `//s.yangshipin.cn${testPath}/txlive`

export function getVideoJs () {
	return new Promise(resolve => {
		const options = {
			src: videoPath + '/js/txplayer.js',
			onLoad: () => {
				resolve()
			}
		}
		if (!window.Txplayer) {
			$getScript(options)
		} else {
			resolve()
		}
	})
}

export function getLiveJs () {
	return new Promise(resolve => {
		const options = {
			src: livePath + '/js/txvlive.js',
			onLoad: () => {
				resolve()
			}
		}
		if (!window.TxvLive) {
			$getScript(options)
		} else {
			resolve()
		}
	})
}

if (!window.videoPlayers) {
	window.videoPlayers = {}
}

async function createPlayer (options) {
	let instance = {}
	instance.id = 'player_' + Math.random().toString(36).replace(/^0\./, '')
	console.log('create player', options)

	// 直播
	if (options.isLive) {
		await getLiveJs()
		const { TxvLive } = window
		instance.isLive = true
		instance.player = new TxvLive({
			jsBasePath: '//s.yangshipin.cn/test/txlive/js/',
			styleUrl: livePath + '/style/txp_mobile_live.css',
			...options
		})

		instance.player.uistatus.on('statechange', (state) => {
			if (state === 'startPlayVideo' || state === 'videoResume') {
				if (!currentPlayer) {
					currentPlayer = instance
				} else if (currentPlayer.id !== instance.id) {
					currentPlayer.stopPlay()
					currentPlayer = instance
				}
			}
		})
	} else {
		// 点播
		await getVideoJs()
		const { Txplayer } = window
		Txplayer.dataset.jsBasePath = videoPath + '/js/'
		instance.isLive = false
		instance.player = new Txplayer({
			...options
		})

		instance.player.on('hdClick', async () => {
			let rs = await Modal.confirm('前往央视频，享受更高清画质', {
				okText: '打开',
				cancelText: '取消'
			})
			if (rs) {
				callApp(`VideoDetailActivity?vid=${options.vid}`)
			}
		})

		instance.player.on('playStateChange', (state) => {
			// -1（未开始）0（已结束）1（正在播放）2（已暂停）3（正在缓冲）
			if ((state === 1) || (state === 3)) {
				if (!currentPlayer) {
					currentPlayer = instance
				} else if (currentPlayer.id !== instance.id) {
					currentPlayer.stopPlay()
					currentPlayer = instance
				}
			}
		})
	}

	// 使用 ready 事件，反而无法切换播放
	// pc端没有问题，移动端，点一下后又停止了播放
	// 使用延迟,pc端和移动端都没有问题
	// 小于 500ms，播放后立即暂停的概率比较高
	instance.play = () => {
		if (instance && instance.player) {
			let player = instance.player
			if (instance.isLive) {
				setTimeout(() => {
					// 播放器已销毁就不再继续
					if (!instance) { return }
					let el = $(player.$el)
					el.find('.txp_btn_play').click()
					el.find('.txp_btn_play_lg').trigger('touchend')
				}, 1000)
			} else {
				let el = $('#' + options.containerId)
				setTimeout(() => {
					if (!instance) { return }
					el.click()
					el.trigger('touchend')
				}, 1000)
			}
		}
	}

	instance.stopPlay = () => {
		if (instance && instance.player) {
			let player = instance.player
			if (instance.isLive) {
				if (player.stopVideo) {
					player.stopVideo()
				}
			} else {
				if (player.pause) {
					player.pause()
				}
			}
		}
	}

	if (!window.videoPlayers) {
		window.videoPlayers = {}
	}
	// 必须要有vid
	window.videoPlayers[options.vid] = instance

	instance.destroy = () => {
		if (instance.player) {
			instance.stopPlay()
			if (instance.player.destroy) {
				instance.player.destroy()
			}
		}
		delete window.videoPlayers[options.vid]
		instance = null
	}

	return instance
}

export default createPlayer
